package com.maybach.core.service.impl;

import com.maybach.common.enums.BaseConstants;
import com.maybach.common.model.PartnerDO;
import com.maybach.common.model.UserDO;
import com.maybach.core.ao.CertificateAO;
import com.maybach.core.manager.PartnerManager;
import com.maybach.core.manager.UserManager;
import com.maybach.dubbo.api.BizResult;
import com.maybach.dubbo.api.enums.AuditStatusEnum;
import com.maybach.dubbo.api.model.*;
import com.maybach.dubbo.api.service.ICertificateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;
import java.util.Set;

/**
 * Created by houenxun on 16/1/26.
 */

@Component
public class CertificateServiceImpl implements ICertificateService {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private CertificateAO certificateAO;
    @Autowired
    private UserManager userManager;
    @Autowired
    private PartnerManager partnerManager;

    @Override
    public BizResult<Void> applyCertificate(PersonCertificateModel person) {
        BizResult<Void> result = new BizResult();
        mockLogin(person.getUserId());
        try {
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            Validator validator = factory.getValidator();
            Set<ConstraintViolation<PersonCertificateModel>> violations = validator.validate(person);
            if (violations.size() > 0) {
                result.setMsg(BaseConstants.getMessage(BaseConstants.ResultCode.PARAM_ERROR));
                return result;
            }
            return certificateAO.submitPersionApprove(person);

        } catch (Exception e) {
            logger.error("处理异常[person=" + person + "]", e);
            result.setMsg(BaseConstants.getMessage(BaseConstants.ResultCode.EXCEPTION));
        }
        return result;
    }


    @Override
    public BizResult applyCertificate(EnterpriseCertificateModel enterprise) {
        BizResult<Void> result = new BizResult();
        mockLogin(enterprise.getUserId());

        try {
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            Validator validator = factory.getValidator();
            Set<ConstraintViolation<EnterpriseCertificateModel>> violations = validator.validate(enterprise);
            if (violations.size() > 0) {
                result.setMsg(BaseConstants.getMessage(BaseConstants.ResultCode.PARAM_ERROR));
                return result;
            }
            return certificateAO.submitEnterpriseApprove(enterprise);

        } catch (Exception e) {
            logger.error("处理异常[person=" + enterprise + "]", e);
            result.setMsg(BaseConstants.getMessage(BaseConstants.ResultCode.EXCEPTION));
        }
        return result;
    }

    @Override
    public BizResult<Void> applyProvider(@NotNull Long userId) {
        BizResult<Void> result = new BizResult();
        mockLogin(userId);
        try {
            if (userId == null || userId <= 0) {
                result.setMsg(BaseConstants.getMessage(BaseConstants.ResultCode.PARAM_ERROR));
                return result;
            }
            return certificateAO.submitProviderApprove(userId);

        } catch (Exception e) {
            logger.error("处理异常[userId=" + userId + "]", e);
            result.setMsg(BaseConstants.getMessage(BaseConstants.ResultCode.EXCEPTION));
        }
        return result;
    }

    @Override
    public BizResult<PersonCertificateModel> queryPersonCertificate(Long userId) {
        BizResult<PersonCertificateModel> result = new BizResult<PersonCertificateModel>();
        try {
            PersonCertificateModel model = certificateAO.queryPersonCertificateByUserId(userId);
            if (null == model) {
                model = new PersonCertificateModel();
                initModel(model);

            }
            result.setResult(model);

        } catch (Exception e) {
            logger.error("查询信息失败[userId=" + userId + "]", e);
            result.setSuccess(false);
            result.setMsg("系统异常");
        }

        return result;
    }


    protected void initModel(BaseAuditModel model) {
        model.setStatus(AuditStatusEnum.never.getStatus());
    }

    @Override
    public BizResult<EnterpriseCertificateModel> queryEnterpriseCertificate(Long userId) {
        BizResult<EnterpriseCertificateModel> result = new BizResult<EnterpriseCertificateModel>();
        try {
            EnterpriseCertificateModel model = certificateAO.queryEnterpriseCertificateByUserId(userId);
            if (null == model) {
                model = new EnterpriseCertificateModel();
                initModel(model);

            }
            result.setResult(model);

        } catch (Exception e) {
            logger.error("查询信息失败[userId=" + userId + "]", e);
            result.setSuccess(false);
            result.setMsg("系统异常");
        }

        return result;
    }

    @Override
    public BizResult<ProviderCertificateModel> queryProviderCertificate(Long userId) {
        BizResult<ProviderCertificateModel> result = new BizResult<ProviderCertificateModel>();
        try {
            ProviderCertificateModel model = certificateAO.queryProviderCertificateByUserId(userId);
            if (null == model) {
                model = new ProviderCertificateModel();
                initModel(model);

            }
            result.setResult(model);

        } catch (Exception e) {
            logger.error("查询信息失败[userId=" + userId + "]", e);
            result.setSuccess(false);
            result.setMsg("系统异常");
        }

        return result;
    }

    @Override
    public BizResult<UserInfoModel> queryUserInfoByUserId(Long userId) {
        BizResult<UserInfoModel> bizResult = new BizResult<>();
        UserInfoModel userInfoModel = new UserInfoModel();
        try{
            UserDO userDO = userManager.selectByPrimaryKey(userId);
            BizResult<PersonCertificateModel> personResult = this.queryPersonCertificate(userId);
            PersonCertificateModel personCertificateModel = new PersonCertificateModel();
            if (personResult.isSuccess()) {
                personCertificateModel = personResult.getResult();
            }
            if (userDO != null) {
                userInfoModel.setMobile(userDO.getMobile());
                userInfoModel.setImages(userDO.getPortraitImgs());
                if (userDO.getRealName() != null) {
                    userInfoModel.setUserName(userDO.getRealName());
                } else {
                    if (personCertificateModel != null) {
                        userInfoModel.setUserName(personCertificateModel.getRealName());
                    }
                }
            } else {
                if (personCertificateModel != null) {
                    userInfoModel.setUserName(personCertificateModel.getRealName());
                }
            }

            Long partnerId = new Long(1l);
            if (userDO != null) {
                partnerId = userDO.getPartnerId();
            }
            if (partnerId != null && partnerId.longValue() != 1) {
                PartnerDO partnerDO = partnerManager.selectByPrimaryKey(partnerId);
                if (partnerDO != null) {
                    userInfoModel.setPartnerName(partnerDO.getCorpName());
                } else {
                    logger.error("查询公司信息为空[partnerId="+partnerId+"]");
                }
            } else {
                // 从企业认证信息中查询
                BizResult<EnterpriseCertificateModel> result = this.queryEnterpriseCertificate(userId);
                EnterpriseCertificateModel enterpriseCertificateModel = new EnterpriseCertificateModel();
                if (result.isSuccess()) {
                    enterpriseCertificateModel = result.getResult();
                    if (enterpriseCertificateModel != null) {
                        userInfoModel.setPartnerName(enterpriseCertificateModel.getCorpName());
                    }
                }
            }
            bizResult.setResult(userInfoModel);
        } catch (Exception e) {
            logger.error("查询信息失败[userId=" + userId + "]", e);
            bizResult.setSuccess(false);
            bizResult.setMsg("系统异常");
        }
        return bizResult;
    }

    private void mockLogin(Long userId) {
        try {
            /*Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken("admin", "111111"));*/

        } catch (Exception e) {
            logger.error("", e);
        }
    }
}
